#include <windows.h>
#include "StdAfx.h"
#define INITGUID
#include <initguid.h>
#include <exdisp.h>
#include <memory.h>
	  HRESULT GetPostData(LPVARIANT pvPostData,CString PostData);

	  int IEWebPost(CString PostData)
	  {
		 HRESULT hr;
		 IWebBrowserApp* pWBApp = NULL; // Derived from IWebBrowser
		 BSTR bstrURL = NULL, bstrHeaders = NULL;
		 VARIANT vFlags = {0},
			vTargetFrameName = {0},
			vPostData = {0},
			vHeaders = {0};

		 if (FAILED(hr = CoInitialize(NULL)))
		 {
			return 1;
		 }

		 if (FAILED(hr = CoCreateInstance(CLSID_InternetExplorer,
			NULL,
			CLSCTX_SERVER,
			IID_IWebBrowserApp,
			(LPVOID*)&pWBApp)))
		 {
			goto Error;
		 }

		 bstrURL = SysAllocString(L"http://61.183.149.138/SetTestData.jspx?action=icmp&");
		 if (!bstrURL)
		 {
			goto Error;
		 }

		 bstrHeaders = SysAllocString(
			L"Content-Type: application/x-www-form-urlencoded\r\n");
		 if (!bstrHeaders)
		 {
			goto Error;
		 }

		 V_VT(&vHeaders) = VT_BSTR;
		 V_BSTR(&vHeaders) = bstrHeaders;

		 hr = GetPostData(&vPostData,PostData);
		 hr = pWBApp->Navigate(bstrURL, &vFlags,
				  &vTargetFrameName, &vPostData, &vHeaders);
		 pWBApp->put_Visible(VARIANT_FALSE);

	  Error:
		 if (bstrURL) SysFreeString(bstrURL);
		 if (bstrHeaders) SysFreeString(bstrHeaders);
		 VariantClear(&vPostData);
		 if (pWBApp) pWBApp->Release();
		 CoUninitialize();

		 return 0;
	  }

	  // Pack some data into a SAFEARRAY of BYTEs. Return in a VARIANT
	  HRESULT GetPostData(LPVARIANT pvPostData,CString PostData)
	  {
		 HRESULT hr;
		 LPSAFEARRAY psa;
 //        LPCTSTR cszPostData = "action=icmp&target=Mocha+Chip&icmptxt=aaabbbcccdddeeefff";
		 LPCTSTR cszPostData = PostData;
		 UINT cElems = lstrlen(cszPostData);
		 LPSTR pPostData;

		 if (!pvPostData)
		 {
			return E_POINTER;
		 }

		 VariantInit(pvPostData);

		 psa = SafeArrayCreateVector(VT_UI1, 0, cElems);
		 if (!psa)
		 {
			return E_OUTOFMEMORY;
		 }

		 hr = SafeArrayAccessData(psa, (LPVOID*)&pPostData);
		 memcpy(pPostData, cszPostData, cElems);
		 hr = SafeArrayUnaccessData(psa);

		 V_VT(pvPostData) = VT_ARRAY | VT_UI1;
		   V_ARRAY(pvPostData) = psa;
		 return NOERROR;
	  }